'use strict'
const code = require('../errorCode.js')
const Service = require('egg').Service

class Login extends Service {
  async login(username, password){
    const {app,service} = this
    const user = await service.mysql.findOne('meta','account',{account:username})
    if (JSON.stringify(user.result)!='{}'){
      if (user.result.password == password){
        const staff = await service.mysql.findById('meta','staff',user.result.staff_id)
        const role = await service.mysql.excute('meta','roleByStaffId',{"staff_id":staff.result.id})
        let roleList=[]
        for (let i=0;i<role.result.rows.length;i++){
          roleList.push(role.result.rows[i].name)
        }
        const auth = await service.mysql.excute('meta','authByRoleName',{role:roleList.join("','")});
        app.setUserCache('user-'+user.result.id,roleList,auth.result.rows);
        const token = app.jwt.sign({
          id:user.result.staff_id,
          organ:staff.result.organ,
          role:roleList
        },app.config.jwt.secret,{expiresIn:'24h'})
        return app.done({token})
      }else{
        return app.error(code.LOGIN_ERR,'用户名或密码错误')
      }
    }
  }
  async logout(userId,token){
    const {app} = this;
    try{
      app.removeUserCache('user-'+userId)
      app.removeTokenCache(token)
      return app.done({user:{id:userId},token,msg:'注销成功！'})
    }catch(e){
      return app.error(code.LOGOUT_ERR,'注销时发生错误！'+e)
    }
  }
}

module.exports = Login